<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>小天使肉包大作战</title>
    <style>
        body {
            margin: 0;
            overflow: hidden;
            background: url('bg.png') no-repeat center center fixed;
            background-size: cover;
            cursor: pointer;
            font-family: Arial, sans-serif;
        }
        #canvas {
            display: block;
        }
        #controls {
            position: fixed;
            bottom: 20px;
            right: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        #counter {
            background: rgba(0,0,0,0.7);
            color: white;
            padding: 10px 15px;
            border-radius: 20px;
        }
        #clear-btn {
            background: rgba(64, 158, 255, 0.8);
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 20px;
            cursor: pointer;
            transition: background 0.3s;
        }
        #clear-btn:hover {
            background: rgba(64, 158, 255, 1);
        }
        #sound-control {
            position: fixed;
            bottom: 20px;
            left: 20px;
            background: rgba(0,0,0,0.7);
            color: white;
            padding: 10px 15px;
            border-radius: 20px;
            cursor: pointer;
        }
        #game-over {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.8);
            display: none;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            color: white;
            z-index: 100;
        }
        #restart-btn {
            margin-top: 20px;
            padding: 15px 30px;
            background: #ff4757;
            color: white;
            border: none;
            border-radius: 30px;
            font-size: 18px;
            cursor: pointer;
            transition: all 0.3s;
        }
        #restart-btn:hover {
            background: #ff6b81;
            transform: scale(1.05);
        }
        #score-display {
            position: fixed;
            top: 20px;
            right: 20px;
            background: rgba(0,0,0,0.7);
            color: white;
            padding: 10px 15px;
            border-radius: 20px;
        }
        #special-timer {
            position: fixed;
            top: 20px;
            left: 20px;
            background: rgba(0,0,0,0.7);
            color: white;
            padding: 10px 15px;
            border-radius: 20px;
            display: none;
        }
        #mode-selector {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0,0,0,0.8);
            padding: 30px;
            border-radius: 20px;
            color: white;
            text-align: center;
            z-index: 200;
        }
        #mode-selector h1 {
            margin-top: 0;
        }
        #mode-selector p {
            margin-bottom: 30px;
            max-width: 500px;
            line-height: 1.6;
        }
        .mode-btn {
            padding: 15px 30px;
            margin: 10px;
            border: none;
            border-radius: 30px;
            font-size: 18px;
            cursor: pointer;
            transition: all 0.3s;
        }
        #pc-mode {
            background: #4CAF50;
            color: white;
        }
        #touch-mode {
            background: #2196F3;
            color: white;
        }
        .mode-btn:hover {
            transform: scale(1.05);
            opacity: 0.9;
        }
        #instructions {
            position: fixed;
            top: 60px;
            left: 20px;
            background: rgba(0,0,0,0.7);
            color: white;
            padding: 10px 15px;
            border-radius: 20px;
            max-width: 300px;
            display: none;
        }
    </style>
</head>
<body>
    <canvas id="canvas"></canvas>
    
    <div id="controls">
        <div id="counter">亚澄数量: 0</div>
        <button id="clear-btn">清除所有</button>
    </div>
    
    <div id="sound-control">🔊 音效: 开</div>
    <div id="score-display">得分: 0</div>
    <div id="special-timer">肉包剩余时间: 15s</div>
    <div id="instructions"></div>
    
    <div id="game-over">
        <h1 style="font-size: 48px; margin-bottom: 20px;">游戏结束!</h1>
        <p id="final-score" style="font-size: 24px;">最终得分: 0</p>
        <button id="restart-btn">重新开始</button>
    </div>

    <div id="mode-selector">
        <h1>小天使の肉包大作战</h1>
        <p>
            <strong>游戏玩法：</strong><br>
            1. 普通模式下，点击屏幕会生成肉包，有5%几率生成肉包<br>
            2. 肉包出现时，所有小天使都会追逐肉包，碰到肉包就被吃了（保护好肉包）<br>
            3. 肉包15秒后会变成锦龙5秒，小天使会逃离锦龙<br>
            4. 锦龙抓到小天使会得分<br><br>
            <strong>触屏模式：</strong><br>
            - 点击不再生成表情<br>
            - 肉包体积减半<br>
            - 生成肉包概率提升到20%<br>
            - 通过滑动屏幕控制肉包移动
        </p>
        <button id="pc-mode" class="mode-btn">电脑模式</button>
        <button id="touch-mode" class="mode-btn">触屏模式</button>
    </div>

    <script>
        // 游戏状态
        let gameState = {
            score: 0,
            isPlaying: false, // 初始为false，等待选择模式
            specialMode: null, // 'meatbun' 或 'jinglong'
            specialTimer: 0,
            autoGenerateInterval: null,
            specialTimerInterval: null,
            soundEnabled: true,
            emojis: [],
            specialItem: null,
            animationFrameId: null,
            gameMode: null, // 'pc' 或 'touch'
            touchControl: {
                touchStartX: 0,
                touchStartY: 0,
                touchMoveX: 0,
                touchMoveY: 0
            }
        };

        // 初始化画布
        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        // 游戏配置
        const EMOJI_COUNT = 156;
        const EMOJI_BASE_PATH = 'emoji/';
        const SOUND_BASE_PATH = 'sounds/';
        const SP_SOUNDS_PATH = 'spsounds/';
        const MIN_SPEED = 1;
        const MAX_SPEED = 3;
        const MEATBUN_SPAWN_CHANCE_PC = 1/20; // 5%
        const MEATBUN_SPAWN_CHANCE_TOUCH = 1/5; // 20%
        const MEATBUN_DURATION = 15000; // 15秒
        const JINGLONG_DURATION = 5000; // 5秒
        const AUTO_GENERATE_INTERVAL = 5000; // 5秒
        const SOUND_COUNT = 10; // 假设有10个普通语音
        
        // 图片资源
        let loadedEmojis = 0;
        const emojiImages = [];
        const meatbunImage = new Image();
        meatbunImage.src = 'image/niguman.png';
        const jinglongImage = new Image();
        jinglongImage.src = 'image/jinglong.png';
        
        // 鼠标/触摸位置
        let mouseX = canvas.width/2;
        let mouseY = canvas.height/2;

        // 预加载所有表情图片
        function preloadEmojis() {
            for (let i = 1; i <= EMOJI_COUNT; i++) {
                const img = new Image();
                img.src = `${EMOJI_BASE_PATH}${i}.png`;
                img.onload = () => {
                    loadedEmojis++;
                    if (loadedEmojis === EMOJI_COUNT) {
                        console.log('所有表情加载完成');
                    }
                };
                emojiImages.push(img);
            }
        }

        // 播放音效
        function playSound(filename, path = SOUND_BASE_PATH, volume = 0.3) {
            if (!gameState.soundEnabled) return;
            
            try {
                const sound = new Audio(`${path}${filename}`);
                sound.volume = volume;
                sound.play().catch(e => console.log('音效播放失败:', e));
            } catch (e) {
                console.error('音效加载错误:', e);
            }
        }

        // 随机播放普通表情语音
        function playRandomVoice() {
            const randomVoiceIndex = Math.floor(Math.random() * SOUND_COUNT) + 1;
            playSound(`${randomVoiceIndex}.mp3`, SOUND_BASE_PATH, 0.5);
        }

        // 创建新表情
        function createEmoji(x, y, isSpecial = false, specialType = 'meatbun') {
            if (emojiImages.length === 0) return;
            
            const randomIndex = Math.floor(Math.random() * emojiImages.length);
            const img = isSpecial ? 
                (specialType === 'meatbun' ? meatbunImage : jinglongImage) : 
                emojiImages[randomIndex];
            
            // 触屏模式下肉包大小减半
            const baseSize = isSpecial && specialType === 'meatbun' && gameState.gameMode === 'touch' ? 40 : 80;
            const size = isSpecial ? baseSize : 50 + Math.random() * 50;
            
            const speedX = MIN_SPEED + Math.random() * (MAX_SPEED - MIN_SPEED);
            const speedY = MIN_SPEED + Math.random() * (MAX_SPEED - MIN_SPEED);
            
            const directionX = Math.random() > 0.5 ? 1 : -1;
            const directionY = Math.random() > 0.5 ? 1 : -1;
            
            const emoji = {
                img: img,
                x: x - size/2,
                y: y - size/2,
                width: size,
                height: size,
                speedX: speedX * directionX,
                speedY: speedY * directionY,
                rotation: 0,
                rotationSpeed: (Math.random() - 0.5) * 5,
                isSpecial: isSpecial,
                specialType: specialType
            };
            
            if (isSpecial) {
                gameState.specialItem = emoji;
                startSpecialTimer(specialType);
                if (specialType === 'meatbun') {
                    playSound('niguman.mp3', SP_SOUNDS_PATH, 0.5);
                }
            } else {
                gameState.emojis.push(emoji);
                playRandomVoice();
            }
            
            updateCounter();
        }

        // 开始特殊模式计时器
        function startSpecialTimer(type) {
            gameState.specialMode = type;
            gameState.specialTimer = type === 'meatbun' ? MEATBUN_DURATION : JINGLONG_DURATION;
            
            const modeName = type === 'meatbun' ? '肉包' : '锦龙';
            document.getElementById('special-timer').textContent = `${modeName}剩余时间: ${gameState.specialTimer/1000}s`;
            document.getElementById('special-timer').style.display = 'block';
            
            clearInterval(gameState.specialTimerInterval);
            gameState.specialTimerInterval = setInterval(() => {
                gameState.specialTimer -= 1000;
                document.getElementById('special-timer').textContent = 
                    `${modeName}剩余时间: ${gameState.specialTimer/1000}s`;
                
                if (gameState.specialTimer <= 0) {
                    if (type === 'meatbun') {
                        // 肉包时间结束，进入锦龙模式
                        createEmoji(mouseX, mouseY, true, 'jinglong');
                    } else {
                        // 锦龙时间结束，恢复正常
                        endSpecialMode();
                    }
                }
            }, 1000);
        }

        // 结束特殊模式
        function endSpecialMode() {
            clearInterval(gameState.specialTimerInterval);
            gameState.specialMode = null;
            gameState.specialItem = null;
            document.getElementById('special-timer').style.display = 'none';
        }

        // 更新计数器
        function updateCounter() {
            document.getElementById('counter').textContent = `表情数量: ${gameState.emojis.length}`;
        }

        // 更新分数
        function updateScore(points) {
            gameState.score += points;
            document.getElementById('score-display').textContent = `得分: ${gameState.score}`;
        }

        // 清除所有表情
        function clearAllEmojis() {
            gameState.emojis = [];
            updateCounter();
        }

        // 切换音效开关
        function toggleSound() {
            gameState.soundEnabled = !gameState.soundEnabled;
            document.getElementById('sound-control').textContent = 
                gameState.soundEnabled ? "🔊 音效: 开" : "🔇 音效: 关";
        }

        // 游戏结束
        function gameOver() {
            gameState.isPlaying = false;
            clearInterval(gameState.autoGenerateInterval);
            clearInterval(gameState.specialTimerInterval);
            cancelAnimationFrame(gameState.animationFrameId);
            
            playSound('gameover.mp3', SP_SOUNDS_PATH, 0.5);
            
            document.getElementById('final-score').textContent = `最终得分: ${gameState.score}`;
            document.getElementById('game-over').style.display = 'flex';
        }

        // 完全重置游戏
        function resetGame() {
            // 清除所有定时器和动画帧
            clearInterval(gameState.autoGenerateInterval);
            clearInterval(gameState.specialTimerInterval);
            cancelAnimationFrame(gameState.animationFrameId);
            
            // 重置游戏状态
            gameState = {
                score: 0,
                isPlaying: true,
                specialMode: null,
                specialTimer: 0,
                autoGenerateInterval: null,
                specialTimerInterval: null,
                soundEnabled: gameState.soundEnabled,
                emojis: [],
                specialItem: null,
                animationFrameId: null,
                gameMode: gameState.gameMode,
                touchControl: {
                    touchStartX: 0,
                    touchStartY: 0,
                    touchMoveX: 0,
                    touchMoveY: 0
                }
            };
            
            // 重置UI
            document.getElementById('game-over').style.display = 'none';
            document.getElementById('special-timer').style.display = 'none';
            document.getElementById('counter').textContent = '表情数量: 0';
            document.getElementById('score-display').textContent = '得分: 0';
            
            // 清除画布
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // 重新开始游戏循环
            startAutoGeneration();
            animate();
            
            // 初始添加3个表情
            setTimeout(() => {
                createEmoji(canvas.width * 0.3, canvas.height * 0.5);
                createEmoji(canvas.width * 0.5, canvas.height * 0.5);
                createEmoji(canvas.width * 0.7, canvas.height * 0.5);
            }, 1000);
        }

        // 开始自动生成表情
        function startAutoGeneration() {
            clearInterval(gameState.autoGenerateInterval);
            gameState.autoGenerateInterval = setInterval(() => {
                if (!gameState.isPlaying) return;
                
                const x = Math.random() * (canvas.width - 100) + 50;
                const y = Math.random() * (canvas.height - 100) + 50;
                
                // 根据模式选择生成肉包的概率
                const spawnChance = gameState.gameMode === 'touch' ? 
                    MEATBUN_SPAWN_CHANCE_TOUCH : MEATBUN_SPAWN_CHANCE_PC;
                
                if (!gameState.specialMode && Math.random() < spawnChance) {
                    createEmoji(x, y, true, 'meatbun');
                } else {
                    createEmoji(x, y);
                }
            }, AUTO_GENERATE_INTERVAL);
        }

        // 检测碰撞
        function checkCollision(emoji1, emoji2) {
            return emoji1.x < emoji2.x + emoji2.width &&
                   emoji1.x + emoji1.width > emoji2.x &&
                   emoji1.y < emoji2.y + emoji2.height &&
                   emoji1.y + emoji1.height > emoji2.y;
        }

        // 动画循环
        function animate() {
            if (!gameState.isPlaying) return;
            
            gameState.animationFrameId = requestAnimationFrame(animate);
            
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // 更新特殊物品位置
            if (gameState.specialItem) {
                if (gameState.gameMode === 'touch') {
                    // 触屏模式：根据触摸边缘移动
                    const edgeThreshold = 50;
                    const moveSpeed = 10;
                    
                    // 检查是否在屏幕边缘附近触摸
                    if (gameState.touchControl.touchMoveX < edgeThreshold) {
                        mouseX -= moveSpeed;
                    } else if (gameState.touchControl.touchMoveX > canvas.width - edgeThreshold) {
                        mouseX += moveSpeed;
                    }
                    
                    if (gameState.touchControl.touchMoveY < edgeThreshold) {
                        mouseY -= moveSpeed;
                    } else if (gameState.touchControl.touchMoveY > canvas.height - edgeThreshold) {
                        mouseY += moveSpeed;
                    }
                }
                
                // 限制位置在画布内
                mouseX = Math.max(0, Math.min(canvas.width, mouseX));
                mouseY = Math.max(0, Math.min(canvas.height, mouseY));
                
                gameState.specialItem.x = mouseX - gameState.specialItem.width/2;
                gameState.specialItem.y = mouseY - gameState.specialItem.height/2;
                
                // 绘制特殊物品
                ctx.save();
                ctx.translate(
                    gameState.specialItem.x + gameState.specialItem.width/2, 
                    gameState.specialItem.y + gameState.specialItem.height/2
                );
                ctx.rotate(gameState.specialItem.rotation * Math.PI / 180);
                ctx.drawImage(
                    gameState.specialItem.img, 
                    -gameState.specialItem.width/2, 
                    -gameState.specialItem.height/2, 
                    gameState.specialItem.width, 
                    gameState.specialItem.height
                );
                ctx.restore();
                
                gameState.specialItem.rotation += gameState.specialItem.rotationSpeed;
            }
            
            // 更新和绘制所有表情
            for (let i = gameState.emojis.length - 1; i >= 0; i--) {
                const emoji = gameState.emojis[i];
                
                // 特殊模式行为
                if (gameState.specialMode === 'meatbun' && gameState.specialItem) {
                    // 肉包模式：追逐肉包
                    const dx = gameState.specialItem.x + gameState.specialItem.width/2 - (emoji.x + emoji.width/2);
                    const dy = gameState.specialItem.y + gameState.specialItem.height/2 - (emoji.y + emoji.height/2);
                    const distance = Math.sqrt(dx * dx + dy * dy);
                    
                    emoji.speedX = (dx / distance) * MAX_SPEED * 1.5;
                    emoji.speedY = (dy / distance) * MAX_SPEED * 1.5;
                    
                    if (checkCollision(emoji, gameState.specialItem)) {
                        gameOver();
                        return;
                    }
                } else if (gameState.specialMode === 'jinglong' && gameState.specialItem) {
                    // 锦龙模式：逃离锦龙
                    const dx = emoji.x + emoji.width/2 - (gameState.specialItem.x + gameState.specialItem.width/2);
                    const dy = emoji.y + emoji.height/2 - (gameState.specialItem.y + gameState.specialItem.height/2);
                    const distance = Math.sqrt(dx * dx + dy * dy);
                    
                    // 逃离速度更快
                    emoji.speedX = (dx / distance) * MAX_SPEED * 2.5;
                    emoji.speedY = (dy / distance) * MAX_SPEED * 2.5;
                    
                    if (checkCollision(emoji, gameState.specialItem)) {
                        playSound('muri.mp3', SP_SOUNDS_PATH, 0.5);
                        gameState.emojis.splice(i, 1);
                        updateScore(1);
                        updateCounter();
                        continue;
                    }
                }
                
                // 更新位置
                emoji.x += emoji.speedX;
                emoji.y += emoji.speedY;
                emoji.rotation += emoji.rotationSpeed;
                
                // 边界检测（反弹）
                if (emoji.x <= 0 || emoji.x + emoji.width >= canvas.width) {
                    emoji.speedX = -emoji.speedX;
                }
                if (emoji.y <= 0 || emoji.y + emoji.height >= canvas.height) {
                    emoji.speedY = -emoji.speedY;
                }
                
                // 绘制表情
                ctx.save();
                ctx.translate(emoji.x + emoji.width/2, emoji.y + emoji.height/2);
                ctx.rotate(emoji.rotation * Math.PI / 180);
                ctx.drawImage(
                    emoji.img, 
                    -emoji.width/2, 
                    -emoji.height/2, 
                    emoji.width, 
                    emoji.height
                );
                ctx.restore();
            }
        }

        // 选择游戏模式
        function selectMode(mode) {
            gameState.gameMode = mode;
            document.getElementById('mode-selector').style.display = 'none';
            
            // 更新操作说明
            const instructions = document.getElementById('instructions');
            if (mode === 'pc') {
                instructions.innerHTML = `
                    <strong>电脑模式操作：</strong><br>
                    - 点击鼠标生成表情<br>
                    - 空格键随机位置生成<br>
                    - ESC键清除所有<br>
                    - 鼠标移动控制肉包
                `;
            } else {
                instructions.innerHTML = `
                    <strong>触屏模式操作：</strong><br>
                    - 触摸屏幕边缘移动肉包<br>
                    - 肉包体积减半<br>
                    - 生成肉包概率20%<br>
                    - 不通过点击生成表情
                `;
            }
            instructions.style.display = 'block';
            
            resetGame();
        }

        // 事件监听
        canvas.addEventListener('click', (e) => {
            if (!gameState.isPlaying || gameState.gameMode === 'touch') return;
            
            mouseX = e.clientX;
            mouseY = e.clientY;
            
            // 电脑模式下点击生成表情
            if (!gameState.specialMode && Math.random() < MEATBUN_SPAWN_CHANCE_PC) {
                createEmoji(mouseX, mouseY, true, 'meatbun');
            } else {
                createEmoji(mouseX, mouseY);
                updateScore(1);
            }
        });

        // 触屏控制
        canvas.addEventListener('touchstart', (e) => {
            if (!gameState.isPlaying || gameState.gameMode !== 'touch') return;
            
            const touch = e.touches[0];
            gameState.touchControl.touchStartX = touch.clientX;
            gameState.touchControl.touchStartY = touch.clientY;
            gameState.touchControl.touchMoveX = touch.clientX;
            gameState.touchControl.touchMoveY = touch.clientY;
        });

        canvas.addEventListener('touchmove', (e) => {
            if (!gameState.isPlaying || gameState.gameMode !== 'touch') return;
            
            const touch = e.touches[0];
            gameState.touchControl.touchMoveX = touch.clientX;
            gameState.touchControl.touchMoveY = touch.clientY;
            e.preventDefault(); // 防止页面滚动
        });

        canvas.addEventListener('touchend', (e) => {
            if (!gameState.isPlaying || gameState.gameMode !== 'touch') return;
            
            gameState.touchControl.touchMoveX = 0;
            gameState.touchControl.touchMoveY = 0;
        });

        canvas.addEventListener('mousemove', (e) => {
            mouseX = e.clientX;
            mouseY = e.clientY;
        });

        document.getElementById('clear-btn').addEventListener('click', clearAllEmojis);
        document.getElementById('sound-control').addEventListener('click', toggleSound);
        document.getElementById('restart-btn').addEventListener('click', resetGame);
        document.getElementById('pc-mode').addEventListener('click', () => selectMode('pc'));
        document.getElementById('touch-mode').addEventListener('click', () => selectMode('touch'));

        window.addEventListener('resize', () => {
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;
        });

        document.addEventListener('keydown', (e) => {
            if (!gameState.isPlaying || gameState.gameMode === 'touch') return;
            
            if (e.code === 'Space') {
                const x = Math.random() * (canvas.width - 100) + 50;
                const y = Math.random() * (canvas.height - 100) + 50;
                
                if (!gameState.specialMode && Math.random() < MEATBUN_SPAWN_CHANCE_PC) {
                    createEmoji(x, y, true, 'meatbun');
                } else {
                    createEmoji(x, y);
                    updateScore(1);
                }
            } else if (e.code === 'Escape') {
                clearAllEmojis();
            }
        });

        // 启动游戏
        preloadEmojis();
    </script>
</body>
</html>